<template>
  <div class="list_scroll_wrap" ref="wrapper">
    <div class="content">
      <!-- 滚动区域 -->
      <template v-if="!errShow">
          <view-list 
          v-if="field === 'view'"
          :viewData="listData[cityId]"
          ></view-list>
          
          <food-list 
          v-if="field === 'food'"
          :foodDatas="listData[cityId]"
          ></food-list>

          <hotel-list v-if="field === 'hotel'"
          :hotelDatas="listData[cityId]"
          ></hotel-list>

          <massage-list v-if="field === 'massage'"
          :massageDatas="listData[cityId]"
          ></massage-list>

          <ktv-list v-if="field === 'ktv'"
          :ktvDatas="listData[cityId]"
          ></ktv-list>

          <!-- loading效果 -->
          <loading-list :loadingShow="loadingShow"></loading-list>
      </template>
      
      <!-- 错误提示 -->
      <error-msg :errShow="errShow"></error-msg>
    </div>
  </div>
</template>

<script>
import BetterScroll from 'better-scroll';
import {ListModel} from '@/models/list.js'
import { mapState } from 'vuex';
import ViewList from './ViewList'
import FoodList from './FoodList'
import HotelList from './HotelList'
import MassageList from './MassageList'
import KtvList from './KtvList'
import ErrorMsg from './Sub/ErrorMes.vue'
import LoadingList from './Sub/Loading.vue'

// 此模块滚动区域，掌管该list页面的数据
export default {
  name: 'ListScrollWrapper',
  components: {
    ViewList,
    FoodList,
    HotelList,
    MassageList,
    KtvList,
    ErrorMsg,
    LoadingList
  },
  data () {
    return {
      // 定义数据缓存池
      // 通过cityId的不同进行获取数据
      listData: {},
      loadingShow: true,
      errShow: false,
    }
  },
  mounted () {
    this.scroll = new BetterScroll(this.$refs.wrapper, {
      scrollY: true
    });

    this.getListData(this.cityId, this.field);
  },
  updated () {
    // 再异步数据回来之后重新计算高度
    this.scroll.refresh();
  },
  computed: {
    ...mapState(['field', 'cityId']),
  },
  methods: {
    async getListData (cityId, field) {
      // 通过城市id的不同将数据放入缓存池中
      if(!this.listData[cityId]) {
        const listModel = new ListModel();
        const res = await listModel.getListData(cityId, field);
        if(res && res.status !== -1) {
          // 数据获取成功
          // 向缓存池中添加数据
          // this.listData[cityId] = res.data;
          // 向对象中添加书vue2的defineProperty监听不到
          this.$set(this.listData, cityId, res.data);

          this.loadingShow = false;
          this.errShow = false;
          // console.log(this.listData);
        } else {
          // 数据获取失败
          this.errShow = true;
        }
      } 
    }
  },
  watch: {
    cityId: {
      handler(newVlaue, oldValue) {
        console.log(this.cityId, this.field);
        this.getListData(this.cityId, this.field);
      }
    }
  }
}
</script>

<style lang="scss" scoped>
.list_scroll_wrap {
  height: calc(100% - .9rem);
  overflow: hidden;
}
</style>